import React, { useState, useRef, useEffect, useCallback } from 'react';

import Modals from '@/components/modals/Modals';
import { SoundOutlined } from '@ant-design/icons';
import { Empty } from 'eaid';
import { MetahumanAvatar } from '@/types/metahuman';
import { App } from 'antd';
import { useMetahumanStore } from '@/store/metahumanStore';
import { SvgIcon } from '@/components/icon';

interface VirtualAvatarModalProps {
  visible: boolean;
  onClose: () => void;
  avatarName?: string;
  voiceType?: string;
  onConfirm?: (avatarName: string, voiceType: string, avatarId: string, speakerId: string) => void;
  avatarOptions?: MetahumanAvatar[];
}

const VirtualAvatarModal: React.FC<VirtualAvatarModalProps> = ({
  visible,
  onClose,
  avatarName = '',
  voiceType = '',
  onConfirm,
  avatarOptions = []
}) => {
  const { message } = App.useApp();
  const [selectedAvatar, setSelectedAvatar] = useState(avatarName);
  const [selectedVoice, setSelectedVoice] = useState(voiceType);
  const [selectedAvatarId, setSelectedAvatarId] = useState(avatarName);
  const [selectedSpeakerId, setSelectedSpeakerId] = useState(voiceType);
  const [isLoading, setIsLoading] = useState(false);
  const [isConfirmLoading, setIsConfirmLoading] = useState(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  
  // 音频播放相关状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentIconIndex, setCurrentIconIndex] = useState(0);
  const [playingVoiceId, setPlayingVoiceId] = useState<string | null>(null);
  const [isAudioLoading, setIsAudioLoading] = useState(false);

  const {
    isLoading: metahumanIsLoading,
    isMetahumanStart,
    setIsMetahumanStart
  } = useMetahumanStore();

  // 根据选中的形象获取对应的音色选项
  const currentVoiceOptions = avatarOptions.find(avatar => avatar.name === selectedAvatar)?.voiceOption || [];

  // 当形象改变时，重置音色选择为第一个可用音色
  const handleAvatarChange = useCallback((avatarName: string, avatarId: string) => {
    console.log('handleAvatarChange', avatarName, avatarId);
    
    // 如果音频正在播放，则重置音频状态
    if (audioRef.current && !audioRef.current.paused) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
    }
    
    setSelectedAvatar(avatarName);
    setSelectedAvatarId(avatarId);
    const newVoiceOptions = avatarOptions.find(avatar => avatar.name === avatarName)?.voiceOption || [];
    if (newVoiceOptions.length > 0) {
      setSelectedVoice(newVoiceOptions[0].name);
      setSelectedSpeakerId(newVoiceOptions[0].speakerId);
    }
  }, [avatarOptions, selectedAvatar]);

  const handleConfirm = useCallback(async () => {
    if (metahumanIsLoading && selectedAvatar !== avatarName) {
      message.info('数字人正在连接中，暂不支持切换数字人');
      onClose();
      return;
    }
    if (!onConfirm) {
      onClose();
      return;
    }
    
    setIsLoading(true);
    setIsMetahumanStart(true);
    try {
      await onConfirm(selectedAvatar, selectedVoice, selectedAvatarId, selectedSpeakerId);
      // onClose();
    } catch (error) {
      console.error('保存虚拟形象设置失败:', error);
      // 这里可以添加错误提示，比如使用 message.error
    } finally {
      setIsConfirmLoading(true);
      setIsLoading(false);
    }
  }, [onConfirm, selectedAvatar, selectedVoice, onClose]);

  useEffect(() => {
    console.log('isMetahumanStart', isMetahumanStart, isConfirmLoading, isLoading);
    if (isConfirmLoading &&!isMetahumanStart && !isLoading) {
      onClose();
    }
  }, [isMetahumanStart, isLoading, isConfirmLoading]);

  // 兜底处理：isConfirmLoading 为 true 后，最多等待1s后调用 onClose()
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isConfirmLoading) {
      timer = setTimeout(() => {
        onClose();
      }, 1000);
    }
    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [isConfirmLoading, onClose]);

  const handleCancel = useCallback(() => {
    // 重置选择
    setSelectedAvatar(avatarName);
    setSelectedVoice(voiceType);
    onClose();
  }, [avatarName, voiceType, onClose]);

  // 图标循环动画效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    
    if (isPlaying) {
      timer = setInterval(() => {
        setCurrentIconIndex((prevIndex) => (prevIndex + 1) % 3);
      }, 400); // 每400ms切换一次图标，使动画更流畅
    } else {
      setCurrentIconIndex(0); // 停止播放时重置到第一个图标
    }

    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [isPlaying]);

  const handleVoicePlay = useCallback((voiceUrl: string, voiceId: string) => {
    // 停止上一个音频
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
    
    // 设置加载状态
    setIsAudioLoading(true);
    setPlayingVoiceId(voiceId);
    
    const audio = new window.Audio(voiceUrl);
    audioRef.current = audio;
    
    // 设置音频事件监听
    audio.addEventListener('loadstart', () => {
      setIsAudioLoading(true);
    });
    
    audio.addEventListener('canplay', () => {
      setIsAudioLoading(false);
    });
    
    audio.addEventListener('play', () => {
      setIsPlaying(true);
      setIsAudioLoading(false);
    });
    
    audio.addEventListener('ended', () => {
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
    });
    
    audio.addEventListener('pause', () => {
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
    });
    
    audio.addEventListener('error', () => {
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
      message.error('音频播放失败');
    });
    
    audio.play().catch((error) => {
      console.error('音频播放失败:', error);
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
      message.error('音频播放失败');
    });
  }, [message]);

  useEffect(() => {
    console.log('visible', visible, avatarOptions, avatarName, voiceType);
    if (visible) {
      setSelectedAvatar(avatarName);
      const avatar = avatarOptions.find(avatar => avatar.name === avatarName);
      const avatarId = avatar?.avatarId || '';
      setSelectedAvatarId(avatarId);
      const newVoiceOptions = avatar?.voiceOption || [];
      if (newVoiceOptions.length > 0) {
        setSelectedVoice(newVoiceOptions[0].name);
        setSelectedSpeakerId(newVoiceOptions[0].speakerId);
      }
    }
    if (!visible && audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
      setIsPlaying(false);
      setPlayingVoiceId(null);
      setCurrentIconIndex(0);
      setIsAudioLoading(false);
    }
  }, [visible]);

  // 获取当前应该显示的图标
  const getCurrentIcon = (voiceId: string) => {
    if (isPlaying && playingVoiceId === voiceId) {
      const icons = ['ai-voice-1', 'ai-voice-2', 'ai-voice-3'];
      return icons[currentIconIndex];
    }
    return ''; // 默认显示第一个图标
  };

  // 获取播放按钮图标
  const getPlayButtonIcon = (voiceId: string) => {
    // 如果正在播放且是当前音色
    if (isPlaying && playingVoiceId === voiceId) {
      return 'ai-voice-stop'; // 显示暂停图标
    }
    
    // 如果正在加载且是当前音色
    if (isAudioLoading && playingVoiceId === voiceId) {
      return 'ai-voice-loading'; // 显示加载图标
    }
    
    // 默认显示播放图标
    return 'ai-voice-default';
  };

  // 处理播放按钮点击
  const handlePlayButtonClick = useCallback((e: React.MouseEvent, voice: any) => {
    e.stopPropagation();
    
    // 如果当前音色正在播放，则暂停
    if (isPlaying && playingVoiceId === voice.speakerId) {
      if (audioRef.current) {
        audioRef.current.pause();
      }
      return;
    }
    
    // 否则开始播放
    handleVoicePlay(voice.previewVoiceUrl, voice.speakerId);
  }, [isPlaying, playingVoiceId, handleVoicePlay]);

  // 处理鼠标悬停状态
  const [hoveredVoiceId, setHoveredVoiceId] = useState<string | null>(null);

  const handleMouseEnter = useCallback((voiceId: string) => {
    if ((!isPlaying && !isAudioLoading) || (playingVoiceId !== voiceId && !isAudioLoading)) {
      setHoveredVoiceId(voiceId);
    }
  }, [isPlaying, isAudioLoading, playingVoiceId]);

  const handleMouseLeave = useCallback(() => {
    setHoveredVoiceId(null);
  }, []);

  return (
    <Modals
      title="设置虚拟形象"
      open={visible}
      onCancel={handleCancel}
      onOk={handleConfirm}
      okText="确认"
      cancelText="取消"
      // cancelLoading={isLoading || isMetahumanStart}
      // footerCancelDisabled={isLoading || isMetahumanStart}
      confirmLoading={isLoading || isMetahumanStart}
      footerOkDisabled={isLoading || isMetahumanStart}
      width={800}
      destroyOnHidden
      centered
    >
      <div className="p-0">
        {/* 选择形象 */}
        <div className="mb-8">
          <div className="mb-2 text-[14px] font-normal text-text-4">选择形象</div>
          <div className="grid grid-cols-1 grid-cols-3 gap-4">
            {avatarOptions.map((avatar) => (
              <div
                key={avatar.avatarId}
                className={`relative border-2 rounded-[12px] p-0 cursor-pointer transition-all ${
                  selectedAvatar === avatar.name
                    ? 'border-blue-500'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
                onClick={() => avatar.name !== '更多形象' && handleAvatarChange(avatar.name, avatar.avatarId)}
              >
                {avatar.previewAvatarUrl ? (
                  <div className="aspect-[3/4] bg-transparent rounded-[12px] flex items-center justify-center mb-2 px-4 pt-2">
                    <img
                      src={avatar.previewAvatarUrl}
                      alt={avatar.name}
                      className="w-full h-full rounded object-cover"
                    />
                  </div>
                ) : (
                  <Empty/>
                )}
                <div className="text-center my-2">
                  <div className="text-sm font-medium text-gray-900">{avatar.name}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 选择音色 */}
        <div className="mb-8">
          <div className="mb-2 text-[14px] font-normal text-text-4">选择音色</div>
          <div className="grid grid-cols-1 grid-cols-3 gap-3">
            {currentVoiceOptions.map((voice) => (
              <div
                key={voice.speakerId}
                data-voice={voice.name}
                className={`flex items-center justify-between p-3 rounded-[12px] border-2 transition-all ${
                  selectedVoice === voice.name
                    ? 'border-blue-500 bg-white'
                    : 'border-gray-200 hover:border-gray-300 bg-bg-3 '
                }`}
                onClick={() => setSelectedVoice(voice.name)}
              >
                <div className="flex items-center gap-2">
                  <span className="text-sm text-gray-700">{voice.name}</span>
                  <SvgIcon 
                    icon={getCurrentIcon(voice.speakerId)} 
                    color='var(--brand-color)'
                    size={22}
                    className='transition-all duration-200'
                    style={{
                      opacity: isPlaying && playingVoiceId === voice.speakerId ? 
                        (currentIconIndex === 0 ? 1 : currentIconIndex === 1 ? 0.6 : 0.3) : 1,
                      transform: isPlaying && playingVoiceId === voice.speakerId ? 
                        `scale(${currentIconIndex === 0 ? 1 : currentIconIndex === 1 ? 0.95 : 0.9})` : 'scale(1)'
                    }}
                  />
                </div>
                {/* 播放按钮 */}
                <div 
                  className="cursor-pointer transition-all duration-200 hover:scale-110"
                  onClick={(e) => handlePlayButtonClick(e, voice)}
                  onMouseEnter={() => handleMouseEnter(voice.speakerId)}
                  onMouseLeave={handleMouseLeave}
                >
                  {/* 默认状态 */}
                  {!isPlaying && playingVoiceId !== voice.speakerId && hoveredVoiceId !== voice.speakerId && (
                    <SvgIcon 
                      size={22}
                      icon="ai-voice-default" 
                      className="transition-all duration-200"
                    />
                  )}
                  
                  {/* 悬停状态 */}
                  {!isPlaying && playingVoiceId !== voice.speakerId && hoveredVoiceId === voice.speakerId && (
                    <SvgIcon 
                      size={22}
                      icon="ai-voice-hover" 
                      color='var(--brand-color)'
                      className="transition-all duration-200"
                    />
                  )}
                  
                  {/* 加载状态 */}
                  {isAudioLoading && playingVoiceId === voice.speakerId && (
                    <SvgIcon 
                      size={22}
                      icon="ai-voice-loading" 
                      color='var(--brand-color)'
                      className="animate-spin transition-all duration-200"
                    />
                  )}
                  
                  {/* 播放/暂停状态 */}
                  {isPlaying && playingVoiceId === voice.speakerId && (
                    <SvgIcon 
                      size={22}
                      icon="ai-voice-stop" 
                      color='var(--brand-color)'
                      className="transition-all duration-200"
                    />
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Modals>
  );
};

export default VirtualAvatarModal; 